using System;
using System.Collections.Generic;
using ExampleApplication.Shared;
using ExamplePlugin.Shared;
using Fadd.Plugins;

namespace ExampleApplication
{
    public class Program : IMyApplication
    {
        private PluginManager<IMyPlugin> _pluginManager;
        private readonly IDictionary<Type, object> _components = new Dictionary<Type, object>();

        [STAThread]
        public static void Main()
        {
            new Program().Start();
        }

        public void AddMenuItem(string name, MenuItemClickedHandler clickHandler)
        {
            // here we should add the menu item to a real application
        }

        /// <summary>
        /// Register a manager that takes care of a business object.
        /// </summary>
        /// <typeparam name="T">Type of service to register</typeparam>
        /// <param name="component">instance of the service</param>
        /// <example>
        /// <code><![CDATA[
        /// components.RegisterComponent<UserManager>(userMgr);
        /// ]]></code>
        /// </example>
        public void RegisterComponent<T>(T component) where T : class
        {
            _components.Add(typeof(T), component);
        }


        /// <summary>
        /// Get a component.
        /// </summary>
        /// <typeparam name="T">Requested service</typeparam>
        /// <returns>object if registered; otherwise null</returns>
        /// <example>
        /// <code><![CDATA[
        /// UserManager mgr = modMgr.GetComponent<UserManager>();
        /// if (mgr != null)
        ///   mgr.Add(new User("FirstName", "LastName"));
        /// ]]></code>
        /// </example>
        public T GetComponent<T>() where T : class
        {
            return (T)_components[typeof(T)];
        }

        private void Start()
        {
            // Create a plugin manager and load it
            _pluginManager = new PluginManager<IMyPlugin>(this);
            _pluginManager.PluginPath = "*Plugin.dll"; // plugins are in the same folder
            _pluginManager.Start();

            // Call a method defined in the plugin
            _pluginManager["MyPlugin"].SayHelloTo("everyone!");

            // Access a registered component.
            IWorldPeace worldPeace = GetComponent<IWorldPeace>();
            worldPeace.Initiate();

            string line = Console.ReadLine();
        }
    }
}
